#include "04_mqtt.h"

volatile MQTTClient_deliveryToken deliveredtoken;
MQTTClient client;		//类似于套节字的作用用于与服务端通信的结构体


void mqtt_connect(const char *username, const char *password, void (*connlost)(void *, char *), int (*msgarrvd)(void *, char *, int , MQTTClient_message *), void (*delivered)(void *, MQTTClient_deliveryToken))
{
    int rc = MQTTClient_create(&client, ADDRESS, CLIENTID,
                               MQTTCLIENT_PERSISTENCE_NONE, NULL);						//创建MQTT客户端
    int ch;
    if(MQTTCLIENT_SUCCESS != rc)														//判断是否创建成功
    {
        printf("create mqtt client failre...\n");
        exit(1);
    }

    MQTTClient_connectOptions conn_opts = MQTTClient_connectOptions_initializer;
    conn_opts.keepAliveInterval = 20;													//设置连接需要发送给服务器的信息
    conn_opts.cleansession = 1;
    conn_opts.username = username;													//根据自己的onenet帐号设置
    conn_opts.password = password;
    rc = MQTTClient_setCallbacks(client, NULL, connlost, msgarrvd, delivered);			//给客户端设置上回调函数
    if(MQTTCLIENT_SUCCESS != rc )
    {
        printf("Failed to connect, return code %d\n", rc);
        exit(EXIT_FAILURE);
    }

    if ((rc = MQTTClient_connect(client, &conn_opts)) != MQTTCLIENT_SUCCESS)			//链接服务器
    {
		printf("1-------\n");
        printf("Failed to connect, return code %d\n", rc);
        exit(EXIT_FAILURE);
    }

	return ;
}

int mqtt_send_message(char *message, int id)
{
    MQTTClient_deliveryToken deliveryToken;
    MQTTClient_message test2_pubmsg = MQTTClient_message_initializer;
    // 需要发送的正文
    test2_pubmsg.qos = QOS;
	test2_pubmsg.retained = 0;
	test2_pubmsg.payload = message;
	test2_pubmsg.payloadlen = strlen(message);
	int rc = MQTTClient_publishMessage(client, PUBLISH, &test2_pubmsg, &deliveryToken);				//上传数据
	if(MQTTCLIENT_SUCCESS != rc)																	//检测上传数据是否成功
	{
		printf("client to publish failure.. %lu\n", pthread_self());
		exit(1);
	}

	printf("Waiting for up to %d seconds for publication on topic %s for client with ClientID: %s\n"
			, (int)(TIMEOUT / 1000), SUBSCRIBE, CLIENTID);
	MQTTClient_waitForCompletion(client, deliveryToken, TIMEOUT);

}
